package yxy.game.pm2.module.conquest;

import java.util.*;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import org.joda.time.DateTime;
import org.joda.time.Minutes;
import org.joda.time.Period;

import org.redisson.api.RMap;
import yxy.apple.util.RandomUtility;
import yxy.apple.util.concurrent.ThreadPoolManager;
import yxy.cherry.battle.module.Position;
import yxy.cherry.battle.module.record.FighterSide;
import yxy.cherry.data.DataCenter;
import yxy.cherry.data.bean.*;
import yxy.cherry.data.script.fomula;
import yxy.cherry.game.base.redis.RedisManager;
import yxy.cherry.game.base.redis.RedisType;
import yxy.game.pm2.Result;
import yxy.game.pm2.bean.Currency;
import yxy.game.pm2.bean.Format.FormatType;
import yxy.game.pm2.bean.PlayerBean;
import yxy.game.pm2.bean.Point;
import yxy.game.pm2.bean.currency.Currencies;
import yxy.game.pm2.bean.currency.CurrencyNotEnoughException;
import yxy.game.pm2.bean.currency.CurrencyType;
import yxy.game.pm2.bean.module.RedisLock;
import yxy.game.pm2.bean.module.rank.active.RankRushEnum;
import yxy.game.pm2.bean.module.rank.active.RankRushHandle;
import yxy.game.pm2.bean.mq.CCReason;
import yxy.game.pm2.bean.task.TaskType;
import yxy.game.pm2.message.BattleMessage;
import yxy.game.pm2.message.ConquestMessage;
import yxy.game.pm2.message.PackageMessage;
import yxy.game.pm2.module.CurrencyHandle;
import yxy.game.pm2.module.bandit.BanditModule;
import yxy.game.pm2.module.battle.*;
import yxy.game.pm2.module.stat.StatHandle;
import yxy.game.pm2.module.task.TaskHandle;

/**
 * 征战
 */
public class ConquestHandle extends BattleModuleHandle {

    final public static int battleExpireDay = 1;// 战斗数据过期时间（天）

    final public static int startMax = 15;// 最高的星级

    protected String code() {
        return BattleType.CONQ.name();
    }

    public BattleMessage.BattleResponse battleResponse(String playerCode) {
        ConquestModule module = ConquestModule.get(playerCode);
        int mapId = module.getMapId();
        BattleHandle battleHandle = new BattleHandle();

        BattleModule battleModule = BattleModule.create(playerCode);
        battleModule.setType(BattleType.CONQ);
        battleModule.setCode(code());

        // 玩家的team
        TeamModule teamA = battleHandle.teamPlayer(playerCode, FormatType.普通);
        battleModule.setTeamA(teamA);

        // 征战地图
        TeamModule teamB = teamConquest(mapId, playerCode);
        battleModule.setTeamB(teamB);

        battleModule.setSettlement(SettlementConquest.create(playerCode, mapId));

//        PlayerBean playerBean = PlayerBean.get(playerCode);
//        int skipLevel = fomula.速战功能等级条件.intValue();
//        int skipVip = fomula.速战功能VIP条件.intValue();
//        battleModule.setSkip(playerBean.getViplevel() >= skipVip || playerBean.getLevel() >= skipLevel);

        battleModule.set(battleExpireDay);

        return battleHandle.battleResponse(battleModule);
    }

    //跳转到某关挑战
    public BattleMessage.BattleResponse battleSkipMapIdResponse(String playerCode, int mapId) throws Exception {
        BattleHandle battleHandle = new BattleHandle();

        BattleModule battleModule = BattleModule.create(playerCode);
        battleModule.setType(BattleType.CONQ);
        battleModule.setCode(code());

        // 玩家的team
        TeamModule teamA = battleHandle.teamPlayer(playerCode, FormatType.普通);
        battleModule.setTeamA(teamA);

        // 征战地图
        TeamModule teamB = teamConquest(mapId, null);
        battleModule.setTeamB(teamB);

        battleModule.setSettlement(SettlementConquest.create(playerCode, mapId));

//        PlayerBean playerBean = PlayerBean.get(playerCode);
//        int skipLevel = fomula.速战功能等级条件.intValue();
//        int skipVip = fomula.速战功能VIP条件.intValue();
//        battleModule.setSkip(playerBean.getViplevel() >= skipVip || playerBean.getLevel() >= skipLevel);

        battleModule.set(battleExpireDay);

        return battleHandle.battleResponse(battleModule);
    }

    //跳转到某关挑战接口的生成录像
    public BattleMessage.BattleExecuteResponse battleSkipMapIdResponseExecute(String playerCode, List<BattleMessage.FighterInfo> formatList) throws Exception {
        //征战模块的战斗信息
        BattleModule module = BattleModule.get(playerCode, code());
        //战斗处理器
        BattleHandle battleHandle = new BattleHandle();
        int[] angersTeamA = battleHandle.angersFromFormatList(formatList, FighterSide.LEFT);
        BattleMessage.BattleExecuteResponse response = battleHandle.battleResponseExecute(module, angersTeamA, null);
        return response;
    }


    public BattleMessage.BattleExecuteResponse battleResponseExecute(String playerCode, BattleMessage.BattleExecuteRequest request) throws Exception {
        BattleModule module = BattleModule.get(playerCode, code());
        return new BattleHandle().battleResponseExecute(module, request);
    }

    public TeamModule teamConquest(int mapid, String playerCode) {
        TeamModule team = new TeamModule();

        map mapdata = DataCenter.getData(mapid, map.class);
        ArrayList<FighterModule> fighterModules = getFighterModuleList(mapid);

        //战力
        long totalPower = 0;

//        //todo 下一版本动态改变怪物战力
//        ConquestDynamicModule conquestDynamicModule = ConquestDynamicModule.get(playerCode);
//        int degree = conquestDynamicModule.getDegree();//难度等级（动态）

        // 武将
        for (int i = 0; i < mapdata.getHeroid().length; i++) {
            Position position = Position.forValue(i + 1);
            int heroid = mapdata.getHeroid()[i];
            if (heroid == -1) continue;
            FighterModule fighterModule = fighterModules.get(i);
            //根据等级提升怪物难度
//            fighterModule.getProperty().addPropertyDataBasicDegree(degree);

            team.addfighter(position, fighterModule);

            totalPower += fighterModule.getTotalPower();
        }
        // 神器
        WeaponModule weapon = WeaponModule.create(mapdata.getWeapondataid(), mapdata.getWeaponlv(), 0, 0, mapdata.getWeaponskilllv());
        team.setWeapon(weapon);

        // 信息
        team.setName(mapdata.getName());
        team.setHead(mapdata.getHeadid());
        team.setPower(totalPower);

        return team;
    }


    /**
     * 处理下一个关卡
     */
    public void nextMap(String playerCode) {

        try {
            ConquestModule conquestModule = ConquestModule.get(playerCode);
            int mapId = conquestModule.getMapId();
            map _mapdata = DataCenter.getData(mapId, map.class);

            int nextId = _mapdata.getNextid();
            if (DataCenter.getData(nextId, map.class) != null) {
                conquestModule.setMapId(nextId);
            }

            conquestModule.set();

//                //todo 记录当天的通关次数,每40关增加一次难度
//                ConquestDynamicModule module = ConquestDynamicModule.get(playerCode);
//                int times = module.getTimes();
//                module.setTimes(times + 1);
//                module.setDegree(times / 40);
//                module.set();

            //不能放异步 因为异步的延迟会导致新手教程的领取赵云显示不准确
            TaskHandle.handle(playerCode, TaskType.指标型_征战_关卡_达到, mapId);

            ThreadPoolManager.getInstance().execute(() -> {
                RankConquest.getRank(playerCode).put(playerCode, mapId);
                StatHandle.stat_关卡统计(playerCode, CCReason.征战, mapId);
            });

        } catch (Exception e) {
        }
    }

    /**
     * 征战阶段奖励
     *
     * @param response
     */
    public Result levelReward(String playerCode, int id, ConquestMessage.ConquestBonusReceiveResponse.Builder response) {
        RedisLock lock = ConquestModule.lock(playerCode);
        try {
            if (lock.tryLock()) {
                ConquestModule conquestModule = ConquestModule.get(playerCode);
                for (int i = 0, size = conquestModule.getLevelReward().size(); i < size; i++) {
                    int levelRewardId = conquestModule.getLevelReward().get(i);
                    if (levelRewardId == id) {
                        // 已经领过
                        return Result.ConquestBonusRewarded;// 通关奖励已经领过
                    }
                }
                levelreward _levelreward = DataCenter.getData(id, levelreward.class);
                if (_levelreward.getCondition() >= conquestModule.getMapId()) {
                    return Result.ConquestBonusForbid;// 通关奖励不能领取
                }
                Collection<Currency> rewards = Currency.create(_levelreward.getRewardtype(), _levelreward.getRewardid(), _levelreward.getRewardnum());
                new CurrencyHandle().addCurrency(playerCode, CCReason.征战, rewards);

                response.addAllRndRewards(new CurrencyHandle().packItems(rewards));
                conquestModule.getLevelReward().add(_levelreward.getId());
                conquestModule.set();

                for (Integer levelRewardId : conquestModule.getLevelReward()) {
                    response.addIds(levelRewardId);
                }

                return Result.Success;
            }
        } catch (Exception e) {
        } finally {
            lock.unlock();
        }

        return Result.DataError;
    }

    /**
     * 征战奖励
     */
    static public Collection<Currency> mapReward(int mapId) {
        ArrayList<Currency> rewards = new ArrayList<>();
        // 固定奖励
        map _mapdata = DataCenter.getData(mapId, map.class);
        if (_mapdata != null) {
            rewards.addAll(Currency.create(_mapdata.getRewardtype(), _mapdata.getRewardid(), _mapdata.getRewardnum()));
        }

        // 随机奖励
        mapproduce _produce = DataCenter.getData(_mapdata.getMapproduceid(), mapproduce.class);
        for (int i = 0; i < _produce.getRewardtype().length; i++) {
            int type = _produce.getRewardtype()[i];// 奖励类型
            if (type <= 0) {
                continue;
            }
            int id = _produce.getRewardid()[i];// 奖励id
            int min = _produce.getRewardnummin()[i];// 最小数量
            int max = _produce.getRewardnummax()[i];// 最大数量
            int prob = _produce.getProbability()[i];// 奖励概率 万分比
            if (RandomUtility.ppm() > prob) {
                continue;
            }
            rewards.add(Currency.create(type, id, RandomUtility.nextInt(min, max + 1)));
        }
        return rewards;
    }

    public long get挂机时长(ConquestModule conquestModule) {
        DateTime startTime = conquestModule.timeline().getStartTime();
        DateTime now = DateTime.now();
        long maxTimeMillis = get挂机最大时长(conquestModule.getPlayerCode());
        long time = now.getMillis() - startTime.getMillis();
        time = time > maxTimeMillis ? maxTimeMillis : time;

        return time;
    }

    public long get挂机最大时长(String playerCode) {
        return vip挂机时长(playerCode);
    }

    public Result idleBonus(String playerCode, ConquestMessage.ConquestIdleBonusResponse.Builder response) {
        int mintime = fomula.挂机时长最小时间.intValue();
        long maxTimeMillis = get挂机最大时长(playerCode);
        long minTimeMillis = Period.seconds(mintime).toStandardDuration().getMillis();
        RedisLock lock = ConquestModule.lock(playerCode);
        try {
            if (lock.tryLock()) {
                ConquestModule conquestModule = ConquestModule.get(playerCode);
                int mapId = conquestModule.getMapId();
                DateTime startTime = conquestModule.timeline().getStartTime();
                DateTime now = DateTime.now();

                long time = now.getMillis() - startTime.getMillis();
                if (time < minTimeMillis) {
                    return Result.ConquestIdleTimeTooClosed;// 领取挂机奖励时间太短了
                }
                if (time > maxTimeMillis) {
                    time = maxTimeMillis;
                }
                Collection<Currency> rewards = vipReward(playerCode, holdReward(mapId, time));
                Collection<Currency> rndRewards = vipReward(playerCode, sweepReward(mapId, time));

                // 结算奖励
                new CurrencyHandle().addCurrency(playerCode, CCReason.征战, rewards);
                new CurrencyHandle().addCurrency(playerCode, CCReason.征战, rndRewards);

                conquestModule.timeline().setStartTime(now);
                conquestModule.set();

                PlayerBean player = PlayerBean.get(playerCode);

                response.setTime(time);
                response.setLevel(player.getLevel());
                response.setExp(Currency.number(playerCode, CurrencyType.CT_主公经验, 0, false));
                response.addAllRewards(new CurrencyHandle().packPoints(rewards));
                response.addAllRndRewards(new CurrencyHandle().packItems(rndRewards));

                return Result.Success;
            }
        } catch (Exception e) {
        } finally {
            lock.unlock();
        }

        return Result.DataError;
    }

    public Result idleBonusAsk(String playerCode) {
        int mintime = fomula.挂机时长最小时间.intValue();
        long maxTimeMillis = get挂机最大时长(playerCode);
        long minTimeMillis = Period.seconds(mintime).toStandardDuration().getMillis();
        ConquestModule conquestModule = ConquestModule.get(playerCode);
        int mapId = conquestModule.getMapId();
        DateTime startTime = conquestModule.timeline().getStartTime();
        DateTime now = DateTime.now();

        long time = now.getMillis() - startTime.getMillis();
        if (time < minTimeMillis) {
            return Result.ConquestIdleTimeTooClosed;// 领取挂机奖励时间太短了
        }
        if (time > maxTimeMillis) {
            time = maxTimeMillis;
        }
        Currencies rewards = vipReward(playerCode, holdReward(mapId, time));
        rewards.addAll(vipReward(playerCode, sweepReward(mapId, time)));
        long 已有情报值 = Point.get(playerCode, CurrencyType.CT_情报, false);
        long 奖励情报值 = reward情报值(rewards);
        BanditModule banditModule = BanditModule.get(playerCode);
        if (奖励情报值 + 已有情报值 > banditModule.情报upper()) {
            return Result.ConquestRewardUpper;// 情报值会超上限
        }
        return Result.Success;
    }

    public Result sweepOnce(String playerCode, ConquestMessage.ConquestSweepOnceResponse.Builder response) {
//		ConquestModule conquestModule = ConquestModule.get(playerCode);
        RedisLock lock = ConquestModule.lock(playerCode);
        try {
            if (lock.tryLock()) {
                ConquestModule conquestModule = ConquestModule.get(playerCode);

                int remain = conquestModule.remainsweeptimes();
                if (remain <= 0) {
                    return Result.ConquestSweepNoTimes;// 扫荡没有次数了
                }
                int times = conquestModule.sweeptimes();
                int costNum = fomula.征战快速作战花费元宝.intValue(times);
                Currency cost = Currency.create(CurrencyType.CT_元宝, 0, costNum);
                try {
                    new CurrencyHandle().cost(playerCode, CCReason.征战, cost);
                } catch (CurrencyNotEnoughException e) {
                    new Result(Result.CostFail, e.getType().getNumber(), e.getDataId());// 消费不足
                }

                int mapId = conquestModule.getMapId();
                long time = Period.seconds(fomula.征战快速作战收益时间.intValue()).toStandardDuration().getMillis();

                Currencies rewards = vipReward(playerCode, holdReward(mapId, time));
                Currencies rndRewards = vipReward(playerCode, sweepReward(mapId, time));

                Collection<PackageMessage.Currency> allRewards = new CurrencyHandle().packPoints(rewards);
                Collection<PackageMessage.Item> allRndRewards = new CurrencyHandle().packItems(rndRewards);

                rewards.addAll(rndRewards);
                // 结算奖励
                new CurrencyHandle().addCurrency(playerCode, CCReason.征战, rewards);

                if (costNum <= 0) {
                    conquestModule.setSweepFreeTimes(conquestModule.getSweepFreeTimes() + 1);
                }
                conquestModule.setSweepTimes(conquestModule.getSweepTimes() + 1);
                conquestModule.setLastSweepTime(DateTime.now());
                conquestModule.set();
                TaskHandle.handle(playerCode, TaskType.统计型_征战_扫荡_次数, 1);

                remain = conquestModule.remainsweeptimes();
                times = conquestModule.sweeptimes();
                boolean privilege = conquestModule.isPrivilege();

                PlayerBean player = PlayerBean.get(playerCode);

                response.setTime(time);
                response.setLevel(player.getLevel());
                response.setExp(Currency.number(playerCode, CurrencyType.CT_主公经验, 0, false));
                response.addAllRewards(allRewards);
                response.addAllRndRewards(allRndRewards);
                response.setTimes(times);
                response.setReleaseTimes(remain);
                response.setPrivilege(privilege);

                return Result.Success;
            }
        } catch (Exception e) {
        } finally {
            lock.unlock();
        }

        return Result.DataError;
    }

    public Result sweepOnceAsk(String playerCode) {
        ConquestModule conquestModule = ConquestModule.get(playerCode);
        int remain = conquestModule.remainsweeptimes();
        if (remain <= 0) {
            return Result.ConquestSweepNoTimes;// 扫荡没有次数了
        }

        int mapId = conquestModule.getMapId();
        long time = Period.seconds(fomula.征战快速作战收益时间.intValue()).toStandardDuration().getMillis();

        Currencies rewards = vipReward(playerCode, holdReward(mapId, time));
        rewards.addAll(vipReward(playerCode, sweepReward(mapId, time)));
        long 已有情报值 = Point.get(playerCode, CurrencyType.CT_情报, false);
        long 奖励情报值 = reward情报值(rewards);
        BanditModule banditModule = BanditModule.get(playerCode);
        if (奖励情报值 + 已有情报值 > banditModule.情报upper()) {
            return Result.ConquestRewardUpper;// 情报值会超上限
        }
        return Result.Success;
    }

    private long reward情报值(Currencies rewards) {
        long 奖励情报值 = 0;
        for (Currency currency : rewards) {
            if (currency.getType().equals(CurrencyType.CT_情报)) {
                奖励情报值 += currency.getNumber();
            }
        }
        return 奖励情报值;
    }

    /**
     * vip特权收益
     */
    private Currencies vipReward(String playerCode, Currencies rewards) {
        PlayerBean playerBean = PlayerBean.get(playerCode);
        int viplevel = playerBean.getViplevel();
        vipdata _vipdata = DataCenter.getData(viplevel, vipdata.class);
        if (_vipdata == null) {
            return rewards;
        }
        for (Currency reward : rewards) {
            switch (reward.getType()) {
                case CT_主公经验:
                    reward.setNumber(reward.getNumber() + reward.getNumber() * _vipdata.getVar1() / 10000);
                    break;
                case CT_钱币:
                    reward.setNumber(reward.getNumber() + reward.getNumber() * _vipdata.getVar2() / 10000);
                    break;
                case CT_武将经验:
                    reward.setNumber(reward.getNumber() + reward.getNumber() * _vipdata.getVar3() / 10000);
                    break;
                default:
            }
        }
        return rewards;
    }

    /**
     * vip特权收益
     */
    private long vip挂机时长(String playerCode) {
        int maxtime = fomula.挂机时长.intValue();
        long maxTimeMillis = Period.seconds(maxtime).toStandardDuration().getMillis();
        PlayerBean playerBean = PlayerBean.get(playerCode);
        int viplevel = playerBean.getViplevel();
        vipdata _vipdata = DataCenter.getData(viplevel, vipdata.class);
        if (_vipdata == null) {
            return maxTimeMillis;
        }
        int addHour = _vipdata.getVar4();
        if (addHour == 0) {
            return maxTimeMillis;
        }
        maxTimeMillis += Period.hours(addHour).toStandardDuration().getMillis();
        return maxTimeMillis;
    }

    /**
     * 扫荡挂机随机奖励
     *
     * @param time 挂机时间（毫秒）
     */
    static public Currencies sweepReward(int mapId, long time) {
        Currencies rewards = new Currencies();
        map _mapdata = DataCenter.getData(mapId, map.class);
        worldproduce _produce = DataCenter.getData(_mapdata.getMapproduceid(), worldproduce.class);

        //打乱奖励，如果抽中装备，后面就不再发装备
        JSONArray equipArrary = new JSONArray();
        JSONArray otherArrary = new JSONArray();

        for (int i = 0, size = _produce.getRewardtype().length; i < size; i++) {
            int minute = _produce.getMininterval()[i];// 结算分钟数
            long millis = Period.minutes(minute).toStandardDuration().getMillis();
            if (millis <= 0 || millis > time) {
                continue;
            }
            long times = time / millis;
            int type = _produce.getRewardtype()[i];// 奖励类型
            if (type <= 0) {
                continue;
            }
            if (type == 7) {//装备类型放装备数组后打乱
                times = times > 6 ? 6 : times;//装备不受vip加成，times最大值为6
                addJsonObject(_produce, equipArrary, i, times);
            }

            if (type != 7) {//其他类型奖励，如将星玉
                addJsonObject(_produce, otherArrary, i, times);
            }
        }

        //装备的奖励打乱
        Collections.shuffle(equipArrary);

        //装备抽取的次数，每次抽其中一件装备
        long times = 0;
        int timeval = _produce.getTimeval();//单位秒
        long millis = Period.seconds(timeval).toStandardDuration().getMillis();//毫秒
        times = millis <= 0 || millis > time ? 0 : time / millis;//次数

        //抽取times轮装备，每轮抽中就不再发装备，如果没中最后装备必中
        for (long i = 0; i < times; i++) {
            for (int y = 0; y < equipArrary.size(); y++) {
                JSONObject equipJSON = equipArrary.getJSONObject(y);

                //根据概率，如果中了后面就不再循环,如果最后一个就不再判断概率，兜底必中
                if (RandomUtility.ppm() > equipJSON.getInteger("probability") && y != equipArrary.size() - 1) {
                    continue;
                }

                //不再用最大值，直接用最小值*次数获得固定数量
                Double num = equipJSON.getIntValue("rewardnummin") / 10000.0;
                long finalNum = (long) Math.ceil(num);//最终的数量
                int rewardtype = equipJSON.getIntValue("rewardtype");//奖励类型
                int rewardid = equipJSON.getIntValue("rewardid");//奖励id
                rewards.add(Currency.create(rewardtype, rewardid, finalNum));
                break;
            }
        }

        //其他奖励抽取
        for (int i = 0; i < otherArrary.size(); i++) {
            JSONObject otherJson = otherArrary.getJSONObject(i);
            long num = 0;
            for (int t = 0; t < otherJson.getIntValue("times"); t++) {
                if (RandomUtility.ppm() > otherJson.getInteger("probability")) {
                    continue;
                }
                num += RandomUtility.nextInt(otherJson.getInteger("rewardnummin"), otherJson.getInteger("rewardnummax") + 1);
            }

            //将星玉特殊处理
            int rewardtype = otherJson.getInteger("rewardtype");
            int rewardid = otherJson.getInteger("rewardid");
            if (rewardtype == 5 && rewardid == 101) {
                num = num / 10000;
            }

            rewards.add(Currency.create(rewardtype, rewardid, num));
        }
        return rewards;
    }


    //封装jsonarrary
    public static void addJsonObject(worldproduce _produce, JSONArray array, int i, long times) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("mininterval", _produce.getMininterval()[i]);// 结算分钟数
        jsonObject.put("rewardtype", _produce.getRewardtype()[i]);// 奖励类型
        jsonObject.put("rewardid", _produce.getRewardid()[i]);// 奖励id
        jsonObject.put("rewardnummin", _produce.getRewardnummin()[i]);// 最小数量 万分比
        jsonObject.put("rewardnummax", _produce.getRewardnummax()[i]);// 最大数量
        jsonObject.put("probability", _produce.getProbability()[i]);// 奖励概率 万分比
        jsonObject.put("times", times);// 次数
        array.add(jsonObject);
    }


    static public Currencies holdReward(int mapId, long time) {
        Currencies rewards = new Currencies();
        map _mapdata = DataCenter.getData(mapId, map.class);
        long duration = Minutes.minutes(1).toStandardDuration().getMillis();
        long coin = _mapdata.getCoin() * time / duration;
        long heroexp = _mapdata.getHeroexp() * time / duration;
        long playerexp = _mapdata.getPlayerexp() * time / duration;
        long letter = _mapdata.getLetter() * time / duration;

        rewards.add(Currency.create(CurrencyType.CT_钱币, 0, coin));
        rewards.add(Currency.create(CurrencyType.CT_武将经验, 0, heroexp));
        rewards.add(Currency.create(CurrencyType.CT_主公经验, 0, playerexp));
        rewards.add(Currency.create(CurrencyType.CT_情报, 0, letter));

        return rewards;
    }


    /**
     * 扫荡挂机随机奖励(仅仅获取将星玉)
     *
     * @param time 挂机时间（毫秒）
     */
    static public Currencies sweepRewardOnlyJade(int mapId, long time) {
        Currencies rewards = new Currencies();
        map _mapdata = DataCenter.getData(mapId, map.class);
        worldproduce _produce = DataCenter.getData(_mapdata.getMapproduceid(), worldproduce.class);
        for (int i = 0, size = _produce.getRewardtype().length; i < size; i++) {
            int minute = _produce.getMininterval()[i];// 结算分钟数
            long millis = Period.minutes(minute).toStandardDuration().getMillis();
            if (millis <= 0 || millis > time) {
                continue;
            }
            long times = time / millis;
            int type = _produce.getRewardtype()[i];// 奖励类型
            if (type <= 0) {
                continue;
            }
            int id = _produce.getRewardid()[i];// 奖励id

            //只要将星玉
            if (id != 101) {
                continue;
            }
            int min = _produce.getRewardnummin()[i];// 最小数量
            int max = _produce.getRewardnummax()[i];// 最大数量
            int prob = _produce.getProbability()[i];// 奖励概率 万分比
            long num = 0;
            for (int t = 0; t < times; t++) {
                if (RandomUtility.ppm() > prob) {
                    continue;
                }
                num += RandomUtility.nextInt(min, max + 1);
            }
            rewards.add(Currency.create(type, id, num / 10000));
        }
        return rewards;
    }


    /**
     * 挂机时间  仅仅钱币
     *
     * @param mapId
     * @param time
     * @return
     */
    static public Currencies holdRewardOnlyCoin(int mapId, long time) {
        Currencies rewards = new Currencies();
        map _mapdata = DataCenter.getData(mapId, map.class);
        long duration = Minutes.minutes(1).toStandardDuration().getMillis();
        long coin = _mapdata.getCoin() * time / duration;
        rewards.add(Currency.create(CurrencyType.CT_钱币, 0, coin));

        return rewards;
    }

    /**
     * 挂机时间  仅仅经验
     *
     * @param mapId
     * @param time
     * @return
     */
    static public Currencies holdRewardOnlyHeroexp(int mapId, long time) {
        Currencies rewards = new Currencies();
        map _mapdata = DataCenter.getData(mapId, map.class);
        long duration = Minutes.minutes(1).toStandardDuration().getMillis();
        long heroexp = _mapdata.getHeroexp() * time / duration;

        rewards.add(Currency.create(CurrencyType.CT_武将经验, 0, heroexp));

        return rewards;
    }


    //获取内存怪物战力属性
    public ArrayList<FighterModule> getFighterModuleList(int mapid) {
        RMap<String, ArrayList<FighterModule>> rMap = RedisManager.getInstance().getConnection(RedisType.REDIS_DATA).client().getMap("INIT:map");
        JSONArray arrary = (JSONArray) JSONArray.toJSON(rMap.get(String.valueOf(mapid)));
        ArrayList<FighterModule> fighterModules = JSON.parseObject(arrary.toString(), new TypeReference<ArrayList<FighterModule>>() {
        });
        return fighterModules;
    }
}
